﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace PdfLibrary
{
    public class PdfString : IPdfObject
    {
        public string Value = null;

        public bool LoadFromReader(PdfReader reader, bool throwException)
        {
            bool isNormalText = reader.TryReadToken("(");
            bool isHexText = reader.TryReadToken("<");

            if (!isNormalText && !isHexText)
                if (throwException) throw new PdfParsingException(reader, "String start tag ( '(' or '<' ) not found!");
                else return false;

            var sb = new StringBuilder();

            var endDelimiter = isNormalText ? ')' : '>';
            
            var lastRead = '\0';
            while (true)
            {
                var c = reader.CurrentChar;
                
                if (c == endDelimiter && lastRead != '\\')
                    break;

                lastRead = c;
                sb.Append(c);

                reader.Position++;
            }

            reader.Position += 1;

            this.Value = sb.ToString();
            this.Value = this.Value.Replace(@"\)", ")");

            if (isHexText)
                this.Value = ConvertHexToString(this.Value);

            this.Value = Regex.Replace(this.Value, @"\\(\d{1,3})", (m) => {
                var dec = Convert.ToInt32(m.Groups[1].Value, 8);
                return new string(new[]{ (char)dec });
            });

            return true;
        }

        public static string ConvertHexToString(String hexInput)
        {
            int numberChars = hexInput.Length;
            
            var bytes = new byte[numberChars / 2];
            for (var i = 0; i < numberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);

            return Encoding.Default.GetString(bytes);
        }
    }
}
